package generic;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * 泛型练习
 */
public class GenericExercise03 {

    public static void main(String[] args) {

        /*
            定义泛型类 DAO<T>,在其中定义一个Map 成员变量，Map的键为String类型，值为 T 类型
            分别创建以下方法：
            public void save(String id, T entity) {} 保存T类型的对象到Map成员变量中
            public T get(String id) {} 从 map 中获取 id 对应的对象
            public void update(String id, T entity) {} 替换Map中 key 为 id 的内容，改为 entity对象
            public List<T> list() 返回Map中存放的所有 T 对象
            public void delete(String id) {} 删除指定 id对象

            定义 User 类
            private 成员变量：id age name

            创建DAO 类的对象，分别调用其 save get update list delete方法来操作User对象
            使用Junit单元测试类进行测试
         */

    }

    @Test
    public void test() {
        DAO<User> d = new DAO<User>();
        User u1 = new User("111", 12, "张三");
        User u2 = new User("222", 13, "李四");
        User u3 = new User("333", 14, "王五");
        User u4 = new User("444", 15, "赵六");
        d.save(u1.getId(), u1);
        d.save(u2.getId(), u2);
        d.save(u3.getId(), u3);
        d.save(u4.getId(), u4);

        User user = d.get("333");
        System.out.println(user);

        d.update("222", new User("222", 18, "王二麻子"));
        user = d.get("222");
        System.out.println(user);

        List<User> list = d.list();
        System.out.println(list);

        d.delete("111");
        System.out.println(list);
    }
}

class User {

    private String id;

    private int age;

    private String name;

    public User(String id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

class DAO<T> {

    Map<String, T> map = new HashMap<>();

    public void save(String id, T entity) {

        if (!map.containsKey(id)) {
            map.put(id, entity);
        }

    }

    public T get(String id) {
        return map.get(id);
    }

    public void update(String id, T entity) {
        if (map.containsKey(id)) {
            map.put(id, entity);
        } else {
            this.save(id, entity);
        }
    }

    public List<T> list() {
        Collection<T> values = map.values();

        ArrayList list = new ArrayList();
        list.addAll(values);
        return list;
    }

    public void delete(String id) {

        map.remove(id);

    }

}

